package com.crm.system.service.impl.user;

import com.alibaba.fastjson.JSONArray;
import com.crm.common.exception.BaseException;
import com.crm.common.model.Enum.ResponseCodeEnum;
import com.crm.common.util.CommonUtils;
import com.crm.common.util.RedisUtil;
import com.crm.model.dto.MainSalesmanDto;
import com.crm.model.entity.sys.SalesmanSupportLog;
import com.crm.model.entity.sys.UserAccount;
import com.crm.model.vo.cluePoolManager.ClueVO;
import com.crm.redis.RedisPrefix;
import com.crm.service.sys.MainSalesmanDbService;
import com.crm.system.service.user.MainSalesmanService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * @author yun_cheng
 * @date 2021年12月22日 上午 11:42:40
 * @description 首页销售明星榜 服务接口实现类
 */
@Service
public class MainSalesmanServiceImpl implements MainSalesmanService {

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    MainSalesmanDbService mainSalesmanDbService;

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public String addSalesmanLog(SalesmanSupportLog salesmanSupportLog) throws Exception {
        if (null == salesmanSupportLog || StringUtils.isBlank(salesmanSupportLog.getSupportedAccountId()) ||
            null == salesmanSupportLog.getType() || StringUtils.isBlank(salesmanSupportLog.getSupportDate())) {
            throw new RuntimeException(ResponseCodeEnum.PARAMETER_ERROR.getResponseCode());
        }

        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        if (salesmanSupportLog.getType().intValue() < 3) { // 点赞 送花不可以重复
            // 验证是否操作过该类型
            boolean isOptionByType = mainSalesmanDbService.isOptionByType(userAccount.getAccountId(),
                    salesmanSupportLog.getSupportedAccountId(), salesmanSupportLog.getType(), salesmanSupportLog.getSupportDate());
            if (isOptionByType) {
                return "该用户已" + (salesmanSupportLog.getType() == 1 ? "点赞" : salesmanSupportLog.getType() == 2 ? "送花" : "");
            }
        } else {
            if (StringUtils.isBlank(salesmanSupportLog.getContent())) {
                return "请输入留言信息！";
            }
        }
        salesmanSupportLog.setId(CommonUtils.getGUID());
        salesmanSupportLog.setSupportAccountId(userAccount.getAccountId());
        salesmanSupportLog.setSupportUserName(userAccount.getUserName());
        boolean flag = mainSalesmanDbService.insertSupportLog(salesmanSupportLog);
        if (flag) {
            return "SUCCESS";
        }
        return "FAIL";
    }

    @Override
    public List<MainSalesmanDto> getSalesmanGiftStat(String date) {
        // 获取销售榜单
        List<MainSalesmanDto> resultList = this.getTopSalesmanList(date);
        if (resultList.size() == 0) {
            return resultList;
        }

        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();

        //获取头像信息
        List<Map<String, String>> accountAccessUrlList = mainSalesmanDbService.getAccessUrlByAccountId(resultList);

        // 根据榜单账号统计已送花和点赞数、留言数
        List<Map<String, Object>> salesmanGiftStatList = mainSalesmanDbService.salesmanGiftStat(resultList, date);

        // 当前账号是否已点赞或者送花花
        List<Map<String, String>> isSupportedInfoList = mainSalesmanDbService.isSupported(userAccount.getAccountId(), resultList, date);

        resultList.stream().forEach(item -> {
            // 判断榜单中是否包含自己 用作判断是否可上传头像
            if (userAccount.getAccountId().equals(item.getAccountId())) {
                item.setIsSelf("1");
            }

            // 拼接头像信息
            if (accountAccessUrlList.size() > 0) {
                for (Map<String, String > accessUrl: accountAccessUrlList) {
                    if (accessUrl.containsKey("accountId") && item.getAccountId().equals(accessUrl.get("accountId"))) {
                        item.setAccessUrl(accessUrl.get("accessUrl"));
                        item.setUserId(accessUrl.get("userId"));
                        break;
                    }
                }
            }

            // 拼接点赞、送花、留言数
            for (Map<String, Object> salesmanGiftStat : salesmanGiftStatList) {
                if (null != salesmanGiftStat && salesmanGiftStat.containsKey("supportedAccountId") &&
                        item.getAccountId().equals(salesmanGiftStat.get("supportedAccountId"))) {
                    String thumbUpCount = salesmanGiftStat.get("type1") != null ? String.valueOf(salesmanGiftStat.get("type1")) : "0";
                    String flowerCount = salesmanGiftStat.get("type2") != null ? String.valueOf(salesmanGiftStat.get("type2")) : "0";
                    String messageCount = salesmanGiftStat.get("type3") != null ? String.valueOf(salesmanGiftStat.get("type3")) : "0";
                    item.setThumbUpCount(thumbUpCount);
                    item.setFlowerCount(flowerCount);
                    item.setMessageCount(messageCount);
                    break;
                }
            }

            // 只会有一条数据
            Map<String, String> isSupported = isSupportedInfoList.get(0);
            if (null != isSupported) {
                String isThumbUpAccountIds = isSupported.get("type1");
                String isFlowerAccountIds = isSupported.get("type2");
                if (StringUtils.isNotBlank(isThumbUpAccountIds) && isThumbUpAccountIds.contains(item.getAccountId())) {
                    item.setIsThumbUp("1");
                }
                if (StringUtils.isNotBlank(isFlowerAccountIds) && isFlowerAccountIds.contains(item.getAccountId())) {
                    item.setIsFlower("1");
                }
            }
        });
        return resultList;
    }

    @Override
    public PageInfo<Map<String, Object>> getTopSalesmanMessage(Integer pageIndex, Integer pageSize) {

        if (pageIndex == null) {
            pageIndex = 1;
        }

        if (pageSize == null) {
            pageSize = 5;
        }

        // 查询留言信息
        PageHelper.startPage(pageIndex, pageSize);
        List<Map<String, Object>> salesmanMessageList = this.mainSalesmanDbService.getTopSalesmanMessage();
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<Map<String, Object>>(salesmanMessageList);
        return pageInfo;
    }

    /**
     * @description 查询个人业绩排行榜（redis） 并返回前三条
     * @param date 查询年月 YYYY-MM
     * @return java.util.List<com.crm.model.dto.MainSalesmanDto>
     * @author ChengYun
     * @date 2021年12月22日 下午 16:33:47
     */
    private List<MainSalesmanDto> getTopSalesmanList(String date) {

        if (StringUtils.isBlank(date)) {
            throw new RuntimeException(ResponseCodeEnum.PARAMETER_ERROR.getResponseCode());
        }

        List<MainSalesmanDto> resultList = new ArrayList<>();
        String redisKey = RedisPrefix.SALESMAN_MONTH + date;
        if (redisUtil.hasKey(redisKey)) {
            String salesmanScoreMoney = redisUtil.get(redisKey);
            resultList = JSONArray.parseArray(salesmanScoreMoney, MainSalesmanDto.class);
            if (resultList.size() >= 2) { // 超过两条数据 则按业绩倒叙排序
                Collections.sort(resultList, new Comparator<MainSalesmanDto>() {
                    public int compare(MainSalesmanDto o1, MainSalesmanDto o2) {
                        return new BigDecimal(o2.getScoreMoney()).compareTo(new BigDecimal(o1.getScoreMoney()));
                    }
                });
                if (resultList.size() > 3) { // 超过三条 则取前三条
                    resultList = resultList.subList(0, 3);
                }
            }
        }
        return resultList;
    }
}
